using UnityEngine;
using UnityEngine.UI;

namespace EntityKit.Runtime
{
    public class TextLocalization : MonoBehaviour
    {
        [Tooltip("本地化文本的键值")] [SerializeField] private string LocalizationID;
        [Tooltip("本地化文本的参数")] private object[] Values;


        [Tooltip("是否初始化刷新")][SerializeField] private bool InitRefresh = true;

        private Text m_Text;

        private void Awake()
        {
            m_Text = GetComponent<Text>();
        }

        private void Start()
        {
            EventKit.AddListener<EventLocalizationLanguageChanged>(OnLocalizationLanguageChanged);
            if (InitRefresh)
            {
                RefreshSafe();
            }
        }

        private void OnDestroy()
        {
            EventKit.RemoveListener<EventLocalizationLanguageChanged>(OnLocalizationLanguageChanged);
        }

        private void OnLocalizationLanguageChanged(IEventMessage obj)
        {
            RefreshSafe();
        }

        private void RefreshSafe()
        {
            if (string.IsNullOrEmpty(LocalizationID))
                return;
            
            if (m_Text == null)
            {
                m_Text = GetComponent<Text>();
            }
            
            if (m_Text != null)
            {
                m_Text.supportRichText = true;
                m_Text.text = LocalizationKit.GetTextValue(LocalizationID, Values);
            }
        }

        /// <summary>
        /// 设置本地化ID
        /// </summary>
        /// <param name="id">本地化ID</param>
        /// <param name="values">本地化参数</param>
        public void SetLocalizationID(string id, params object[] values)
        {
            LocalizationID = id;
            Values = values;
            RefreshSafe();
        }
    }
}